package jwf;

import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

import jwf.action.Action;
import jwf.action.impl.Action404;
import jwf.action.impl.FooAction;
import jwf.fcgi.FCGXRequest;
import jwf.http.Http;
import jwf.http.Request;
import jwf.http.Response;

public class ServerTest {

    public static List<Action> actionList = new ArrayList<Action>();

    public static Action findAction(String uri) {
	for (Action action : actionList) {
	    if (action.match(uri)) {
		return action;
	    }
	}
	return Action404.defaultInstance;
    }

    public static void foo() throws Exception {
	ServerSocket serverSocket = new ServerSocket(4000);
	while (true) {
	    Socket socket = serverSocket.accept();
	    FCGXRequest fcgxRequest = new FCGXRequest(socket);
	    fcgxRequest.init();
	    Request req = new Request(fcgxRequest);
	    Response res = new Response(fcgxRequest);
	    // res.getHeader()
	    // .add(Http.HH_CONTENT_TYPE, "text/html charset=utf-8");
	    // res.getHeader().setHttpStatusCode(Http.HC_OK);
	    // res.outputHeader();
	    // res.writeRaw(req.uri());
	    Action action = findAction(req.uri());
	    action.process(req, res);
	    fcgxRequest.destroy();
	}

    }

    /**
     * @param args
     */
    public static void main(String[] args) {
	try {
	    actionList.add(new FooAction());
	    foo();
	} catch (Exception e) {
	    e.printStackTrace();
	}

    }

}

/*
 * 
 * System.out.println("socket accept"); System.out.println("local port:" +
 * socket.getLocalPort()); System.out.println("port:" + socket.getPort());
 * 
 * byte[] inBuff = new byte[40960]; int len =
 * socket.getInputStream().read(inBuff, 0, 40960); System.out.println("len:" +
 * len);
 * 
 * System.out.println(Hex.format(inBuff, len));
 * 
 * byte[] buff = new byte[16]; buff[0] = 1; buff[1] = 3; buff[2] = 0; buff[3] =
 * 1; buff[4] = 0; buff[5] = 8; buff[6] = 0; buff[7] = 0; for (int i = 8; i <
 * 16; ++i) { buff[i] = 0; } socket.getOutputStream().write(buff, 0,
 * buff.length); socket.getOutputStream().flush(); socket.close();
 */
